package com.chart.web.controller.chart.sta;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.chart.chart.domian.ChartConfigs;
import com.chart.chart.service.IChartConfigsService;
import com.chart.common.core.controller.BaseController;
import com.chart.common.core.domain.AjaxResult;
import com.chart.common.utils.ExcelDataUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 漏斗图
 *
 * @author chart
 */
@RestController
@RequestMapping("/funnel/chart")
public class FunnelChartController extends BaseController
{


    @Autowired
    private IChartConfigsService chartConfigsService;




    @PostMapping("/importData1")
    public AjaxResult importData(MultipartFile file,Long configId) throws Exception {
        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = workbook.getSheetAt(1);
            //获取
            List<List<String>> getdata = ExcelDataUtils.getData(sheet);

            if (CollectionUtils.isEmpty(getdata)) {
                return AjaxResult.error("请填充数据");
            }

            List<JSONObject> list = new ArrayList<>();


            for (int i = 2; i < getdata.size(); i++) {
                List<String> strings = getdata.get(i);
                JSONObject jsonObject = new JSONObject();
                for (int i1 = 0; i1 < strings.size(); i1++) {
                    String s = strings.get(i1);
                    if (ObjectUtils.isNotEmpty(s) && !s.equals("")) {
                        if (i1 == 0) {
                            jsonObject.put("name", s);
                        } else if(i1 == 1) {
                            jsonObject.put("value", Double.parseDouble(s));
                        }
                    }
                }
                list.add(jsonObject);
            }


            ChartConfigs configs = chartConfigsService.getById(configId);
            JSONObject jsonObject = JSON.parseObject(configs.getConfigValue());


            List<JSONObject> series = (List<JSONObject>) jsonObject.get("series");
            for (int i = 0; i < series.size(); i++) {
                JSONObject jsonObject1 = series.get(i);
                jsonObject1.put("data", list);
            }

            jsonObject.put("series", series);

            return AjaxResult.success(JSON.toJSONString(jsonObject));
        }finally {
            workbook.close();
        }
    }

}
